﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using Convert.DataAccess;
using Convert.LOTSmodel;
using Convert.CPIAMmodel;
using System.Configuration;
using System.Data.OleDb;
using System.Windows;
namespace Convert.DBconverter
{
    class RegisterTransactionsConverter
    {
        private static int BATCH_SAVE_SIZE = 5000;
        public static string LotsConnectionString; //= @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\LOTS\lots.mdb";//@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\LOTS\lots.mdb";//ConfigurationManager.ConnectionStrings["LOTStoCPIAMconvert.Properties.Settings.lotsConnectionString"].ConnectionString;
        public static string CpiamConnectionString; //= ConfigurationManager.ConnectionStrings["LOTStoCPIAMconvert.Properties.Settings.CPIAMPOSMaxRetailConnectionString"].ConnectionString;
        public static Dictionary<int, StockFileDetail> LotsItemDetails;
        public static Dictionary<int, TransactionDetail> LotsTransactionDetails;
        private static Dictionary<int, Guid> SaleIDToDebtorHeaderID;
        public static void ConvertRegisterTransactions(string lotsConnectionString, string cpiamConnectionString, Dictionary<int, StockFileDetail> lotsItemDetails, Dictionary<int, TransactionDetail> lotsTransactionDetails, Dictionary<int, Guid> saleIDToDebtorHeaderID)
        {
            LotsConnectionString = lotsConnectionString;
            CpiamConnectionString = cpiamConnectionString;
            LotsTransactionDetails = lotsTransactionDetails;
            LotsItemDetails = lotsItemDetails;
            SaleIDToDebtorHeaderID = saleIDToDebtorHeaderID;
            DataTable RegisterTransactionsDT = RegisterDataTables.CreateRegisterTransactionsDT();
            OleDbConnection dbConn = new OleDbConnection(LotsConnectionString);
            try
            {
                dbConn.Open();
                using (OleDbCommand command = dbConn.CreateCommand())
                {
                    command.CommandText = string.Format(@" SELECT SaleID, Retail, (Retail*Quantity) AS Total, GSTPaid, Discount, Quantity, StockID, Description
                                                            FROM SaleItem");
                    OleDbDataReader reader = command.ExecuteReader();
                    DateTime start = DateTime.Now;
                    while (reader.Read())
                    {
                        SaleItem saleItem = new SaleItem();
                        saleItem.SaleID = reader.GetInt32(0);
                        saleItem.Retail = reader.GetInt32(1);
                        saleItem.Total = reader.GetDouble(2);
                        saleItem.Tax = reader.GetInt32(3);
                        saleItem.Discount = reader.GetFloat(4);
                        saleItem.Quantity = reader.GetFloat(5);
                        saleItem.StockID = reader.GetInt32(6);
                        saleItem.Description = reader.GetString(7);
                        SaveTransactionEntry(saleItem, RegisterTransactionsDT);
                        if (RegisterTransactionsDT.Rows.Count % BATCH_SAVE_SIZE == 0)
                        {
                            SaveAllDataTables(CpiamConnectionString, RegisterTransactionsDT);
                        }
                    }
                    SaveAllDataTables(CpiamConnectionString, RegisterTransactionsDT);
                }
            }
            catch (Exception ex)
            {
                Logger.LogWarningAndError("Error in Convert RegisterTransactions ", ex);
                MessageBox.Show("Error converting RegisterTransactions: " + ex.Message + "\n\nStackTrace=" + ex.StackTrace);
            }
            finally
            {
                dbConn.Close();
            }
        }

        public static void SaveTransactionEntry(SaleItem saleItem, DataTable RegisterTransactionsDT)
        {
            if (LotsTransactionDetails.ContainsKey(saleItem.SaleID))
            {
                long lngReceiptNo = saleItem.SaleID;
                int registeringStoreID = 1;
                Guid guidClerkID = Guid.Empty;
                String strClientNo = "";
                DateTime transactionDate = DateTime.Now;

                if (LotsTransactionDetails.ContainsKey(saleItem.SaleID))
                {
                    TransactionDetail transDetail = LotsTransactionDetails[saleItem.SaleID];
                    guidClerkID = transDetail.ClerkID;
                    strClientNo = transDetail.StrClientNo;
                    transactionDate = transDetail.Date;
                }

                String strGSTCode = "N";
                String strDesc = saleItem.Description;

                int intDeptNo = 0;
                String strItemCode = String.Empty;
                int intStkNo = 0;


                decimal decQty = (decimal)(saleItem.Quantity);
                decimal decCost = (decimal)(saleItem.Cost / 100);
                decimal decSellPrice = (decimal)(saleItem.Retail / 100);
                decimal decExtAmt = (decimal)(saleItem.Total / 100);
                decimal decGSTAmt = (decimal)(saleItem.Tax / 100);
                decimal decGovCont = 0;
                decimal decDiscAmt = (decimal)(saleItem.Discount / 100);
                decimal decDiscPerc = decSellPrice != 0 ? 100 * (decDiscAmt / Math.Abs(decSellPrice)) : 0;


                if (LotsItemDetails.ContainsKey(saleItem.StockID))
                {
                    StockFileDetail detail = LotsItemDetails[saleItem.StockID];
                    intDeptNo = detail.DeptNo;
                    strItemCode = detail.StkNo.ToString();
                    intStkNo = detail.StkNo;
                    strGSTCode = detail.GSTCode;
                }
                else
                {
                    intDeptNo = 9999;
                    strItemCode = "M";
                    intStkNo = 0;
                    decCost = 0;
                    if (decGSTAmt > 0)
                        strGSTCode = "Y";
                }

                //trans qty must be an integer. If the qty is a decimal value, then include this in the description and have qty of 1
                short transQty;
                if (decQty>32767)
                {
                    strDesc += string.Format("Qty: " + decQty.ToString());
                    transQty = 1;
                }
                else
                    transQty = (short)decQty;

                String strGSTMarker = decGSTAmt == 0 ? String.Empty : "*";

                bool blnEthical = false;
                Guid guidDebtorID = SaleIDToDebtorHeaderID.ContainsKey(saleItem.SaleID) ? SaleIDToDebtorHeaderID[saleItem.SaleID] : Guid.Empty;
                String strTransMarker = String.Empty;


                RegisterTransactionsDT.Rows.Add(lngReceiptNo, registeringStoreID, transactionDate, intDeptNo, strItemCode, intStkNo, strDesc, transQty, decCost, decCost, strGSTCode,
                                            decGSTAmt, strGSTMarker, decSellPrice, decDiscPerc, decDiscAmt, decExtAmt, decGovCont, guidClerkID, blnEthical,
                                            Guid.Empty, guidDebtorID, strClientNo, Guid.Empty, -1, strTransMarker);
            }

        }

        private static void SaveAllDataTables(String cpiamPosMaxRetailReceiptsConnectionString, DataTable registerTransactionsDT)
        {
            if (registerTransactionsDT.Rows.Count > 0)
                dbSaveBatch.SaveBatch(registerTransactionsDT, "RegisterTransactions", cpiamPosMaxRetailReceiptsConnectionString);

        }
    }
}
